package flc.ast.utils;

import androidx.annotation.WorkerThread;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import flc.ast.bean.PicAlbumBean;

public class MyMediaLoader {

    private static MyMediaLoader sInstance;
    private final List<PicAlbumBean> classBeanList = new ArrayList<>();

    private MyMediaLoader() {

    }

    public synchronized static MyMediaLoader getInstance() {
        if (sInstance == null) {
            sInstance = new MyMediaLoader();
        }
        return sInstance;
    }

    @WorkerThread
    public List<PicAlbumBean> loadPicData(boolean forceAgainGet, String path) {
        if (!forceAgainGet) {
            if (classBeanList.size() > 0) {
                return classBeanList;
            }
        }
        classBeanList.clear();

        List<File> files = getHistoryPic(path);

        Map<String, List<PicAlbumBean.ClassBean>> timeCategoryMap = new HashMap<>();
        for (File file : files) {
            String picTime = TimeUtils.millis2String(FileUtils.getFileLastModified(file), "yyyy/MM/dd（EEEE）");

            List<PicAlbumBean.ClassBean> beanList = null;
            if (timeCategoryMap.containsKey(picTime)) {
                beanList = timeCategoryMap.get(picTime);
            } else {
                beanList = new ArrayList<>();
                timeCategoryMap.put(picTime, beanList);
            }

            PicAlbumBean.ClassBean classBean = new PicAlbumBean.ClassBean(file.getName(),
                    file.getPath(), FileUtils.getFileLastModified(file));
            beanList.add(classBean);
        }
        Iterator<String> iterator = timeCategoryMap.keySet().iterator();
        String time = null;
        while (iterator.hasNext()) {
            time = iterator.next();
            classBeanList.add(new PicAlbumBean(time, timeCategoryMap.get(time)));
        }
        SortUtils.getSortShotBefore(classBeanList);
        return classBeanList;
    }

    private List<File> getHistoryPic(String path) {
        boolean orExistsDir = FileUtils.createOrExistsDir(PathUtils.getFilesPathExternalFirst() + Content.myAlbum + "/" + path);
        if (orExistsDir) {
            return FileUtils.listFilesInDir(PathUtils.getFilesPathExternalFirst() + Content.myAlbum + "/" + path);
        }
        return null;
    }
}
